package com.example.ljw.frescowallpaper.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.example.ljw.frescowallpaper.R;
import com.example.ljw.frescowallpaper.adapter.MyConstellationAdapter;
import com.example.ljw.frescowallpaper.adapter.MyRecyclerAdapter;
import com.example.ljw.frescowallpaper.adapter.MySelectAdapter;
import com.example.ljw.frescowallpaper.adapter.MySortAdapter;
import com.example.ljw.frescowallpaper.bean.ConstellationBean;
import com.example.ljw.frescowallpaper.bean.MyFirstBean;
import com.example.ljw.frescowallpaper.bean.MySelectBean;
import com.example.ljw.frescowallpaper.bean.SortBean;
import com.example.ljw.frescowallpaper.config.URLConfig;
import com.example.ljw.frescowallpaper.utils.IMyRetrofit;
import com.example.ljw.frescowallpaper.widget.DividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by LJW on 2016/11/15.
 */

public class WallFragment extends Fragment {
    //刷新用到的limit
    private int limit=30;
    //首页参数的Map集合
    private Map<String,String> mapFirst=new HashMap<>();
    //精选参数的Map集合
    private Map<String,String> mapSelect=new HashMap<>();
    //星座名字
    private String name="白羊座";
    private static final String TAG = "===========";
    //星座的TV
//    private TextView tv_fragment_constellation;
    //progressbar
    private ProgressBar progressBar_fragment;
    private Retrofit mRetrofit=null;
    //首先设置上下文参数
    private Context mContext=null;
    //设置初始的页数
    private int mTabindex = 1;
    private int mCurpage = 1;
    private int mLastVisibleItem = 0;

    //初始化主页recycleView
    private RecyclerView recyclerView_fragment;
    //初始化分类页面的recycleView
    private RecyclerView recyclerView_fragment_sort;
    //初始化星座页面的recycleview
    private  RecyclerView recyclerView_fragment_constellation;
    //recycleView适配器
    private MyRecyclerAdapter recycleAdapter;
    //数据源
    private List<MyFirstBean.ResBean.DataBean> mFirstList=new ArrayList<>();
    private List<SortBean.ResBean.DataBean> mSortList=new ArrayList<>();
    private List<MySelectBean.ResBean.DataBean> mSelectList=new ArrayList<>();
    //星座的适配器
    private MyConstellationAdapter myConstellationAdapter;
    //星座的头数据源
    private List<Object> mConstellationHeadList=new ArrayList<>();
//    //星座的幸运图片的集合
   private List<ConstellationBean.DataBean.WallpaperBlogsBean> mConstellationPhotoList=new ArrayList<>();
    public WallFragment(){

    }
    public static WallFragment newInstance(int tabindex) {
        WallFragment fragment = new WallFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("mTabindex", tabindex);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(mContext);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext=getActivity();
        //得到穿过来的页数
        if(getArguments()!=null){
            mTabindex=getArguments().getInt("mTabindex");
        }
        EventBus.getDefault().register(this);

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String name) {

        initData(name);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        switch (mTabindex){
            //首页
            case 1:
                return inflater.inflate(R.layout.fragment_wall,container,false);

            //精品
            case 2:
                return inflater.inflate(R.layout.fragment_wall,container,false);


            //分类
            case 3:
                return inflater.inflate(R.layout.fragment_sort,container,false);


            //星座
            case 4:
                return inflater.inflate(R.layout.fragment_constellation,container,false);


        }
       return null;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //初始化recycleView
        recyclerView_fragment= (RecyclerView) view.findViewById(R.id.recyclerView_fragment);
        recyclerView_fragment_sort= (RecyclerView) view.findViewById(R.id.recyclerView_fragment_sort);
        recyclerView_fragment_constellation= (RecyclerView) view.findViewById(R.id.recyclerView_fragment_constellation);

//        //初始化progressbar
        progressBar_fragment= (ProgressBar) view.findViewById(R.id.progressBar_fragment);
        progressBar_fragment.setVisibility(View.VISIBLE);
    }


    @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        switch (mTabindex){
            //首页
            case 1:
                initMapFirst();
                initFirstRetrofit();
                initRecycle();
                loadNetData(mapFirst);
                break;
            //精品
            case 2:
                initMapSelect();
                initSelectRetrofit();
                initRecycle();
                loadSelectNetData(mapSelect);
                break;
            //分类
            case 3:
               initSortRetrofit();
               initSortRecycle();
               loadSortNetData(URLConfig.URL_SORT);
                break;
            //星座
            case 4:
                initConstellationRetrofit();
//                initRecyclerConstellation();
                initData(name);
                break;
        }


    }

    private void initMapSelect() {
        mapSelect.put(URLConfig.URLFirst.HEIGHT,"1334");
        mapSelect.put(URLConfig.URLFirst.LIMIT,limit+"");
        mapSelect.put(URLConfig.URLFirst.ORDER,"hot");
        mapSelect.put(URLConfig.URLFirst.SKIP,"0");
        mapSelect.put(URLConfig.URLFirst.SYS_LANGUAGE,"zh-Hans-CN");
        mapSelect.put(URLConfig.URLFirst.WIDTH,"750");
    }

    private void initMapFirst() {
        mapFirst.put(URLConfig.URLFirst.HEIGHT,"1334");
        mapFirst.put(URLConfig.URLFirst.LIMIT,limit+"");
        mapFirst.put(URLConfig.URLFirst.ORDER,"new");
        mapFirst.put(URLConfig.URLFirst.SKIP,"0");
        mapFirst.put(URLConfig.URLFirst.SYS_LANGUAGE,"zh-Hans-CN");
        mapFirst.put(URLConfig.URLFirst.WIDTH,"750");
    }


    private void initSelectRetrofit() {
        //为okhttp设置拦截器
        OkHttpClient client=new OkHttpClient.Builder()
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        Log.i(TAG,request.url().toString());
                        return chain.proceed(request);
                    }
                })
                .build();

        mRetrofit=new Retrofit.Builder()
                .baseUrl(URLConfig.URL_SORT_BASE)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
    }

            private void loadSelectNetData(Map<String,String> map) {
        IMyRetrofit iMyRetrofit=mRetrofit.create(IMyRetrofit.class);
        Observable observable=iMyRetrofit.getSelectBeanObservable(map);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<MySelectBean>() {
                    @Override
                    public void onCompleted() {
                        recyclerView_fragment.scrollToPosition(mLastVisibleItem);
                        progressBar_fragment.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(MySelectBean mySelectBean) {
//                        mSelectList.clear();
                        //设置布局管理器
                        final GridLayoutManager gridLayoutManager=new GridLayoutManager(mContext,2);
                        recyclerView_fragment.setLayoutManager(gridLayoutManager);
                        mSelectList.addAll(mySelectBean.getRes().getData());
//                        Toast.makeText(mContext, "精选数据加载陈宫"+mSelectList.size(), Toast.LENGTH_SHORT).show();
                        Log.e(TAG,"精选数据的list集合大小"+mSelectList);
                        //绑定适配器
                        final MySelectAdapter mAdapter=new MySelectAdapter(mContext,mSelectList);
                        recyclerView_fragment.setAdapter(mAdapter);
                        if(mCurpage>1){
                           mAdapter.reloadRecyclerView(mSelectList,false);
                        }
                        recyclerView_fragment.addOnScrollListener(new RecyclerView.OnScrollListener() {
                            @Override
                            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                super.onScrollStateChanged(recyclerView, newState);
                                if (newState == RecyclerView.SCROLL_STATE_IDLE
                                        && mLastVisibleItem == mAdapter.getItemCount()-1){
                                    recyclerView.postDelayed(null,1);
                                    mCurpage++;
                                    limit+=30;
                                    initMapSelect();
                                    loadSelectNetData(mapSelect);
//                                    Toast.makeText(mContext, "精选页面下拉完成"+mCurpage, Toast.LENGTH_SHORT).show();

                                }
                            }

                            @Override
                            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                super.onScrolled(recyclerView, dx, dy);
                                if(gridLayoutManager.findLastVisibleItemPosition()!=-1) {
                                    mLastVisibleItem = gridLayoutManager.findLastVisibleItemPosition();
                                }
                            }
                        });
                    }

                });
    }

    private void initData(String name) {
        IMyRetrofit iMyRetrofit=mRetrofit.create(IMyRetrofit.class);
        Observable observable=iMyRetrofit.getConstellationObservable(name);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ConstellationBean>() {
                    @Override
                    public void onCompleted() {
                        progressBar_fragment.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ConstellationBean constellationBean) {

                        Log.i(TAG,constellationBean.toString());

                        mConstellationHeadList.clear();

                        //数据源
                        ConstellationBean.DataBean.AstroBean astroBean=constellationBean.getData().getAstro();
                        mConstellationPhotoList=constellationBean.getData().getWallpaperBlogs();
                        mConstellationHeadList.add(astroBean);
                        mConstellationHeadList.add(astroBean);
                        mConstellationHeadList.addAll(mConstellationPhotoList);
                        mConstellationHeadList.add(astroBean);
                        mConstellationHeadList.size();
                        //设置布局管理器
                        GridLayoutManager gridLayoutManager=new GridLayoutManager(mContext,2);
                        //初始化适配器
                       myConstellationAdapter=new MyConstellationAdapter(mContext,mConstellationHeadList);
                        //合并第一行
                        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                            @Override
                            public int getSpanSize(int position) {
                                if(myConstellationAdapter.getItemViewType(position)==MyConstellationAdapter.TYPE1||
                                        myConstellationAdapter.getItemViewType(position)==MyConstellationAdapter.TYPE2){
                                    return 2;
                                }else {
                                    return 1;
                                }
                            }
                        });


                        if(recyclerView_fragment_constellation==null)
                            return;

                        recyclerView_fragment_constellation.setLayoutManager(gridLayoutManager);
                        recyclerView_fragment_constellation.setAdapter(myConstellationAdapter);

                       myConstellationAdapter.notifyDataSetChanged();
                    }


                });
    }



    //初始化星座Retrofit
    private void initConstellationRetrofit() {
        mRetrofit=new Retrofit.Builder()
                .baseUrl(URLConfig.URL_BASE_SELECT)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        //设置recycleView
        recyclerView_fragment_constellation.setHasFixedSize(true);
        recyclerView_fragment_constellation.setItemAnimator(new DefaultItemAnimator());
        recyclerView_fragment_constellation.addItemDecoration(new DividerItemDecoration(mContext,
                DividerItemDecoration.VERTICAL_LIST));
    }

    //初始化分类页面的Retroft
    private void initSortRetrofit() {
        mRetrofit=new Retrofit.Builder()
                .baseUrl(URLConfig.URL_SORT_BASE)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
    }

    //加载分类页面的数据
    private void loadSortNetData(String url) {
        //初始化数据用Rxjava和retrofit加载
        IMyRetrofit iMyRetrofit=mRetrofit.create(IMyRetrofit.class);
        Observable observable=iMyRetrofit.getSortBeanObservable(url);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SortBean>() {
                    @Override
                    public void onCompleted() {
                        progressBar_fragment.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(SortBean sortBean) {
                        mSortList=sortBean.getRes().getData();
                        //绑定适配器
                        MySortAdapter sortAdapter=new MySortAdapter(mContext,mSortList);
                        recyclerView_fragment_sort.setAdapter(sortAdapter);

                    }


                });


    }

    //初始化分类数据
    private void initSortRecycle() {
        //设置recycleView
        recyclerView_fragment_sort.setHasFixedSize(true);
        recyclerView_fragment_sort.setItemAnimator(new DefaultItemAnimator());
        recyclerView_fragment_sort.addItemDecoration(new DividerItemDecoration(mContext,
                DividerItemDecoration.VERTICAL_LIST));
        //设置布局管理器
        LinearLayoutManager manage=new LinearLayoutManager(mContext,
                LinearLayoutManager.VERTICAL,false);
        recyclerView_fragment_sort.setLayoutManager(manage);

    }


    private void initFirstRetrofit() {


        //初始化retrofit
//        OkHttpClient client=OkHttp3Utils.getOkHttpSingletonInstance();
        mRetrofit=new Retrofit.Builder()
                .baseUrl(URLConfig.URL_SORT_BASE)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
    }

    private void initRecycle() {
        //设置recycleView
        recyclerView_fragment.setHasFixedSize(true);
        recyclerView_fragment.setItemAnimator(new DefaultItemAnimator());
        recyclerView_fragment.addItemDecoration(new DividerItemDecoration(mContext,
                DividerItemDecoration.VERTICAL_LIST));

    }

    private void loadNetData(Map<String,String> map) {
        //初始化数据用Rxjava和retrofit加载
        IMyRetrofit iMyRetrofit=mRetrofit.create(IMyRetrofit.class);
        Observable observable=iMyRetrofit.getFirstBeanObservable(map);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<MyFirstBean>() {
                    @Override
                    public void onCompleted() {
                        progressBar_fragment.setVisibility(View.INVISIBLE);
                        recyclerView_fragment.scrollToPosition(mLastVisibleItem);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(MyFirstBean myFirstBean) {
                        mFirstList.clear();
                        //数据成功加载
//                        Toast.makeText(mContext, "数据加载成功", Toast.LENGTH_SHORT).show();
                        mFirstList=myFirstBean.getRes().getData();

                        //

                        //设置布局管理器
                        final GridLayoutManager gridLayoutManager=new GridLayoutManager(mContext,2);
                        recyclerView_fragment.setLayoutManager(gridLayoutManager);
                        //设置适配器
                        recycleAdapter=new MyRecyclerAdapter(mContext,mFirstList);
                        recyclerView_fragment.setAdapter(recycleAdapter);
                        if(mCurpage>1){
                            recycleAdapter.reloadRecyclerView(mFirstList,false);
                        }
                        //上拉监听
                        recyclerView_fragment.addOnScrollListener(new RecyclerView.OnScrollListener() {

                            @Override
                            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                super.onScrollStateChanged(recyclerView, newState);
                                if (newState == RecyclerView.SCROLL_STATE_IDLE
                                        && mLastVisibleItem == recycleAdapter.getItemCount() - 1) {
                                    recyclerView.postDelayed(null,1);
                                    mCurpage++;
                                    limit+=30;
                                    progressBar_fragment.setVisibility(View.VISIBLE);
                                    initMapFirst();
                                    loadNetData(mapFirst);

                                }
                            }

                            @Override
                            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                super.onScrolled(recyclerView, dx, dy);
                                if(gridLayoutManager.findLastVisibleItemPosition()!=-1) {
                                    mLastVisibleItem = gridLayoutManager.findLastVisibleItemPosition();

                                }

                            }

                        });
//                        recyclerView_fragment.addOnScrollListener(new RecyclerView.OnScrollListener() {
//                            @Override
//                            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                                super.onScrollStateChanged(recyclerView, newState);
//                                if (newState == RecyclerView.SCROLL_STATE_IDLE
//                                        && mLastVisibleItem == recycleAdapter.getItemCount() - 1) {
//                                    mCurpage++;
//                                    loadNetworkData();
//                                }
//                            }
//
//                            @Override
//                            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                                super.onScrolled(recyclerView, dx, dy);
//                                mLastVisibleItem = gridLayoutManager.findLastVisibleItemPosition();
//                            }
//                        });


                   }



                });
    }


}


